//
//  OYTabBar.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/11/30.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit

protocol OYTabBarDelegate: NSObjectProtocol {
    func OYTabBarDelegate(oyTabBar:OYTabBar)
}


class OYTabBar: UITabBar {

    weak var oyDelegate: OYTabBarDelegate?
    
    // 懒加载button
    lazy var composeBtn: UIButton = {
        let addButton = UIButton()
        
        addButton.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal)
        addButton.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: .highlighted)
        addButton.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal)
        addButton.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .highlighted)
        addButton.sizeToFit()
        
        addButton.addTarget(self, action: #selector(composeAction), for: .touchUpInside)
        
        return addButton
    }()
    
    // MARK: -添加回调属性
    var callBack:(()->())?
    
    // MARK: -添加button响应事件
    func composeAction() {
        
        // 点击button时执行回调
        callBack?()
        
        // 点击button时执行代理
        oyDelegate?.OYTabBarDelegate(oyTabBar: self)
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI()  {

        addSubview(composeBtn)
        
    }

    // 对自定义tabbar进行布局
    override func layoutSubviews() {
        
        
        super.layoutSubviews()
        
        // 确定composBtn的位置
        composeBtn.centerX = bounds.size.width * 0.5
        composeBtn.centerY = bounds.size.height * 0.5
        
        let itemWidth = width / 5
        let itemHeight = height
        
        var index = 0
        // 遍历子控件，为四个TabBarButton布局
        for subview in self.subviews {

            if subview .isKind(of: NSClassFromString("UITabBarButton")!) {
                subview.width = itemWidth
                subview.height = itemHeight
                subview.x = CGFloat(index) * itemWidth
                
                index += 1
                
                if index == 2 {
                    index += 1
                }
            }
            
        }
        
    }
}
